﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DimensionData
{
    public class D02View : DimView
    {
        public D02View(List<DimData> dims)
            : base(dims)
        {
            // 构建一个合计项目
            DimViewItem totalItem = new DimViewItem() { DimData = new DimData() };
            totalItem.Level = 0;
            totalItem.Range = 0;
            Items.Add(totalItem);

            Stack<DimData> dimStack = new Stack<DimData>();
            for (int i = this._dims.Count - 1; i >= 0; i--)
            {
                dimStack.Push(this._dims[i]); ;
            }

            while (dimStack.Count > 0)
            {
                DimData dim = dimStack.Pop();
                
                DimViewItem item = new DimViewItem()
                {
                    DimData = dim
                };

                item.Level = dim.Level + 1;
                item.Range = dim.Range;
                Items.Add(item);

                if (dim.Level == 0)
                {
                    // 更新合计项目的区域
                    // +1是因为要包含自身
                    totalItem.Range += item.Range + 1;
                }

                for (int i = dim.Children.Count - 1; i >= 0; i--)
                {
                    dimStack.Push(dim.Children[i]);
                }
            }
        }

        public override DataTable Pull()
        {
            DataTable table = new DataTable();
            table.Columns.Add("c");
            table.Columns.Add("l");
            table.Columns.Add("n");
            Stack<DimData> dimStack = new Stack<DimData>();
            for (int i = this._dims.Count - 1; i >= 0;i-- )
            {
                dimStack.Push(this._dims[i]); ;
            }

            while (dimStack.Count > 0)
            {
                DimData dim = dimStack.Pop();

                DataRow row = table.NewRow();
                row["c"] = 0;
                row["l"] = dim.Level;
                row["n"] = dim.Name;
                table.Rows.Add(row);

                for (int i = dim.Children.Count - 1; i >= 0; i--)
                {
                    dimStack.Push(dim.Children[i]);
                }
            }

            return table;
        }
    }
}
